/*
 Developer: John Archer (john.archer.jpa@gmail.com)
 
 This file is part of VTBuilder.

 VTBuilder is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License.

 VTBuilder is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with VTBuilder.  If not, see <http://www.gnu.org/licenses/>.
 */
package core.tasks;

import core.para.Para;
import core.rb.MB;
import core.sb.SB;
import core.tasks.pack.TScriptPack;
import gui.processor.Processor;
import gui.utils.ProgBar;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TScripts {

    public TScripts() {
    }

    public SB tscripts(MB mb, ArrayList<String> refs, Processor p) throws Exception {
        int start, end, prevEnd = 0;
        
        CountDownLatch cdl = new CountDownLatch(refs.size());
        ArrayList <TScriptPack> packs = new <TScriptPack> ArrayList();
        for (int x = 0; x < refs.size(); x++) {
            start = prevEnd + Para.SEPERATOR.length();
            prevEnd = end = start + refs.get(x).length();
            MB temp = mb.subMB(start, end);
            temp.refLen = (end - start);
            packs.add(new TScriptPack(cdl, temp, p));
        }
        
        DecimalFormat format = null;
        if(Para.GUI){
            p.dPrgA(ProgBar.START, packs.size());
        }
        else{format = new DecimalFormat("##.##");}
        int done = 0;
        ExecutorService executorService = Executors.newFixedThreadPool(Para.TRDS);
        do{
            executorService.execute(packs.get(done));
            done++;
            if(Para.GUI){p.dPrgA(ProgBar.UPDATE, done);}
            else{System.out.print("\r constructing transcripts: "+ format.format(((double)done/packs.size()) * 100) + "%");}
        }while(done < packs.size());
        cdl.await();
        executorService.shutdown();
        SB tScripts = new SB();
        for (TScriptPack pac : packs) {
            tScripts.seqs.addAll(pac.pOut.seqs);
        }
        if(Para.GUI){
            p.dPrgA(ProgBar.END, 0);
        }
        else{System.out.println("\n");}
        return tScripts;
    }
}